<?php

namespace admin\dao;

/**--tmpl-use--**/
use herosphp\core\Loader;

/**--tmpl-import--**/

class RoleDao extends CommonDao{

	/*
	* @override add
	 */
	public function add($data){
		$id = parent::add($data);
		if(!$id) return false;
		if(isset($data['node'])){
			$adminRoleNodeDao = Loader::model('adminRoleNode');
			foreach($data['node'] as $v){
				$adminRoleNodeDao->add(array('role_id' => $id,'node_id' => $v));
			}
		}
		return $id;
	}

	/*
	 * @override update
	 */
	public function update($data,$id){
		if($data['node']){
			$adminRoleNodeDao = Loader::model('adminRoleNode');

			$adminRoleNodeDao->deletes(array('role_id' => $id));

			foreach($data['node'] as $v){
				$adminRoleNodeDao->add(array('role_id' => $id,'node_id' => $v));
			}
		}
		return parent::update($data,$id);
	}
	public function delete($id)
	{
		$adminRoleNodeDao = Loader::model('adminRoleNode');
		$role_condi['role_id'] = $id;

		$this->beginTransaction();
		if($adminRoleNodeDao->deletes($role_condi))
		{
			$rs = parent::delete($id);
			if($rs)
			{
				$this->commit();
				return true;
			}
		}
		$this->rollback();
		return false;
	
	}
	/*
	 * @override deletes
	 */
	public function deletes($ids)
	{
		$adminRoleNodeDao = Loader::model('adminRoleNode');
		$role_condi['role_id'] = $ids['id'];

		$this->beginTransaction();
		if($adminRoleNodeDao->deletes($role_condi))
		{
			$rs = parent::deletes($ids);
			if($rs)
			{
				$this->commit();
				return true;
			}
		}
		$this->rollback();
		return false;

	}
	/*
	 * @override getItems
	 */
	public function getItems($conditions, $fields, $order, $limit, $group, $having)
	{
		$items = parent::getItems($conditions, $fields, $order, $limit, $group, $having);
		if(!$items) return NULL;
	
		/**--tmpl-todo--**/
	
		/**-- foreigncondi --**/
		$manger_managercondi = array();
		foreach($items as $k => $v)
		{
			if($v['manager_id'])
			{
				$manager_managercondi[] = $v['manager_id'];
			}
		}
		
		$adminDao = Loader::model('adminManager');
		$manager = $adminDao->getItems(array('id' => array('$in' => $manager_managercondi)));
		
		/**-- foreignforeach  --**/
		foreach ($items as $k => $v)
		{
			/**--tmpl-foreignfill--**/
		
			foreach($manager as $kk => $vv)
			{
				if($vv['id'] == $v['manager_id'])
				{
					$items[$k]['manager_name'] = $vv['name'];
				}
			}
			
		}
		return $items;
	}
	/*
	 * 判断是否存在角色关联管理员
	 * @param $ids : 角色id数组
	 * 
	 */
	public function isBelongSomeone($ids)
	{
		$adminManagerRole = Loader::model('adminManager');

		return !!$adminManagerRole->count(array('role_id' => array('$in' => $ids),'del_status' => 0));
		
	}

}
